package cn.qyd.threadsignal;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author 邱运铎
 * @date 2024-03-19 12:12
 */
public class CyclicBarrierDemo {
    static class Task implements Runnable{
        private final CyclicBarrier cyclicBarrier;

        public Task(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }
        @Override
        public void run() {
            try {
                //todo 任务
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + " 已完成任务，正在屏障1处等待");
                cyclicBarrier.await();
                System.out.println(Thread.currentThread().getName() + "已越过屏障1");
                //todo 任务2
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + "已完成任务2，正在屏障2处等待");
                cyclicBarrier.await();
                System.out.println(Thread.currentThread().getName() + "已越过屏障2");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    public static int count = 1;
    public static void main(String[] args) {
        int numberThreads = 3;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(numberThreads,() -> {
            System.out.println("所有线程已经到达第" + count++ +"屏障...");
        });

        Thread t1 = new Thread(new Task(cyclicBarrier));
        Thread t2 = new Thread(new Task(cyclicBarrier));
        Thread t3 = new Thread(new Task(cyclicBarrier));

        t1.start();
        t2.start();
        t3.start();
    }
}
